<template>
  <MoveDialog
    :visible.sync="importShow"
    :before-close="closeDialog"
    width="600px"
  >
    <span slot="title" style="color: #303753; font-size: 14px; font-weight: 600"
      >批量导入</span
    >
    <div class="range-area">
      <el-tabs v-model="activeName">
        <el-tab-pane label="导入客户" name="first">
          <div class="tip">
            <div class="import-batch">
              <span>导入批次 </span>
              <el-input
                clearable
                v-model="importNum"
                type="text"
                size="small"
                style="margin: 0 6px"
                :maxlength="20"
                :disabled="autoDisabled"
              ></el-input>
              <span>
                <el-checkbox
                  v-model="autoGeneration"
                  @change="handleAutoGeneration"
                ></el-checkbox>
                自动生成
                <el-tooltip
                  content="自动生成规则为年月日时分秒"
                  placement="top"
                >
                  <i
                    style="
                      font-size: 12px;
                      color: #b3b9c7;
                      padding-right: 6px;
                      cursor: pointer;
                    "
                    class="V7_iconfont V7_iconV7tubiao_bangzhu-42"
                  ></i>
                </el-tooltip>
              </span>
            </div>
            <h5 style="font-size: 14px; margin: 10px 0">
              <i
                class="V7_iconfont V7_iconV7tubiao_zhongyaoxiaoxi"
                style="color: #faae14; font-size: 14px"
              ></i>
              导入规则说明：
            </h5>
            1.请下载相应的模板，您可自行删除模板中的非必填字段，不会影响数据导入；<br />
            2.只支持后缀为xls、xlsx的Excel文件，文件最多上传10000条数据；<br />
            3.请按模板内说明的要求填充内容，红色字体的字段内容为必填项，其他字段选填，并将所有单元格格式设置为文本格式，避免导入值与显示值不一致；<br />
            4.导入时，将根据您在【系统设置】-【客户管理】-【客户基本规则】的【客户查重规则】进行查重，如果设置的重复处理规则为"更新客户信息"，
            还需要设置"更新客户信息权限"；<br />
            5.一个客户有多个手机号码、邮箱、微信号、QQ的话,每个用指定的字符(支持英文逗号“,”斜杠“/”顿号“、”3种符号)隔开,如(10086,10000、01010000)，
            若需导入备注用“|”分隔，如(10086|移动客服,10000|电信客服)；<br />
            6.字段类型为复选框的 填写内容为多个值时,应以英文分号(;)隔开；<br />
            7.字段类型为级联菜单的 填写内容为多级值时,应以顿号(、)隔开；<br />
            8.字段类型为日期（范围）导入格式为：yy-mm-dd~yy-mm-dd,日期时间（范围）的导入格式为yy-mm-dd
            hh:mm:ss~yy-mm-dd hh:mm:ss，范围需要以波浪号（~）隔开；<br />
            9.日期需要符合yyyy-MM-dd 格式,日期时间要符合yyyy-MM-dd
            HH:mm:ss格式；<br />
            10.只支持单sheet页导入；<br /><br />
            注意:导入后产生的错误报告只保留30天，30天内可以下载。<br />
          </div>
          <div style="display: flex; margin-top: 16px">
            <el-upload
              accept=".xls, .xlsx"
              :action="batchUrl"
              :limit="1"
              :on-success="handleSuccess"
              :on-remove="handleRemove"
              :file-list="fileList"
              :headers="{
                sessionid: userId,
                loginToken: loginToken,
              }"
            >
              <el-button
                type="primary"
                style="margin-right: 8px"
                slot="trigger"
                size="mini"
                >导入客户</el-button
              >
              <el-button size="mini" @click="downLoadTemplet">
                下载模板
              </el-button>
            </el-upload>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="btns" slot="footer">
      <el-button size="mini" @click="closeDialog">取消</el-button>
      <el-button size="mini" type="primary" @click="importSave">确定</el-button>
    </div>
  </MoveDialog>
</template>

<script lang="ts">
/**
 * 导入客户组件
 */
import { Component, Vue } from 'vue-property-decorator'
import { commonAction, deepClone, getFormatDateTime } from '@/utils/common'
import MoveDialog from '@/components/globalTool/moveDialog/index.vue'
import { ExportExcel } from '../../../../public/static/js/worker' // 导出
@Component({
  name: 'ImportCustomer',
  components: {
    MoveDialog
  }
})
export default class ImportCustomer extends Vue {
  [x: string]: any
  private importShow: boolean = false

  private activeName: any = 'first'

  private importNum: any = ''

  private autoGeneration: boolean = true

  private autoDisabled: boolean = true

  private filepath: any = ''

  private fileList: any = []

  private customerRepeatRules: any = []

  get account () {
    return (this.$store as any).state.common.session.account._id
  }

  get userId () {
    return (this.$store as any).state.common.session.user._id
  }

  get loginToken () {
    return (this.$store as any).state.common.session.user.loginToken
  }

  get batchUrl () {
    return '/upload?accountId=' + this.account + '&module=customer'
  }

  get importFields () {
    return (this.$store as any).state.common.publicCache.customerImports || []
  }

  private excelMergeVal: any = {
    content:
      `
      说明:
       1.以下所有单元格格式必须设置为文本类型;
       2.红色字段为客户唯一标识，必须填写且不可重复;
       3.*号为必填项，不填写则导入失败
       4.字段类型为复选框的 填写内容为多个值时,应以英文分号(;)隔开
       5.字段类型为级联菜单的 填写内容为多级值时,应以顿号(、)隔开
       6.字段类型为日期（范围）导入格式为：yy-mm-dd~yy-mm-dd,日期时间（范围）的导入格式为yy-mm-dd hh:mm:ss~yy-mm-dd hh:mm:ss，范围需要以波浪号（~）隔开
       7.日期需要符合yyyy-MM-dd格式,日期时间要符合yyyy-MM-dd HH:mm:ss格式
       8.支持一个客户导入多条手机号码、微信号、邮箱、QQ，每个用指定的字符(支持英文逗号“,” 斜杠“/”2种符号)隔开,如(10086,10000、01010000)，若需导入备注用竖线“|”分隔，如(10086|移动客服,10000|电信客服)
       9.只支持单sheet页导入
      `,
    region: 'A1:P1',
    col: 2,
    style: {
      fontColor: 'FF0000'
    },
    line: 1, // 设置行高的行
    height: 200 // 行高
  }

  public clearData () {
    this.autoDisabled = true
    this.autoGeneration = true
    this.filepath = ''
    this.fileList = []
    this.importNum = ''
  }

  private handleAutoGeneration (val: any) {
    if (val) {
      this.autoDisabled = true
    } else {
      this.autoDisabled = false
    }
  }

  private downLoadTemplet () {
    const headers = deepClone(this.importFields)
    headers.forEach(val => {
      val.prop = val.field
      if (this.customerRepeatRules.includes(val.field)) {
        val.headerStyle = {
          fontColor: 'FF0000'
        }
      } else {
        val.headerStyle = {
          fontColor: '0055FF'
        }
      }
      if (val.required) {
        val.label = '*' + val.name
      } else {
        val.label = val.name
      }
    })
    const de = new ExportExcel(headers, [], this.excelMergeVal)
    de.toExport('导入客户模板')
  }

  private async openDraw (data: any = []) {
    this.importShow = true
  }

  private closeDialog () {
    this.importShow = false
  }

  private handleSuccess (res) {
    const success = res.success
    const data = res.data
    if (success) {
      this.filepath = data.path
    }
  }

  private handleRemove () {
    this.filepath = ''
  }

  private handleValue (val: any) {
    if (!/^[\u4E00-\u9FA5a-zA-Z0-9]+$/g.test(val)) {
      return this.$message.error('只能输入中文、大小写英文和数字')
    }
  }

  private importSave () {
    let importBatchNumber = this.importNum
    if (this.autoGeneration) {
      importBatchNumber = getFormatDateTime(new Date(new Date().getTime()), '').replace(/-|:|\s/g, '')
    }
    if (!importBatchNumber) {
      return this.$message.error('请输入导入批次')
    } else {
      if (!/^[\u4E00-\u9FA5a-zA-Z0-9]+$/g.test(importBatchNumber)) {
        return this.$message.error('只能输入中文、大小写英文和数字')
      }
    }
    if (!this.filepath) {
      return this.$message.error('请导入客户')
    }
    const params = {
      url: '/base/action/transmission/import/task/create',
      method: 'post',
      data: {
        type: 'customer',
        extra: {
          importBatchNumber
        },
        filepath: this.filepath
      }
    }
    commonAction(params).then(res => {
      if (res.success) {
        const h = this.$createElement;
        (this.$message as any)({
          message: h('div', { style: 'color:#2ed47a' }, [
            h('span', {}, '导入成功，请前往'),
            h('a', { on: { click: this.jumpToTransmissionCenter }, style: 'cursor:pointer,color:#008cee' }, '传输中心'),
            h('span', {}, '查看')
          ]),
          type: 'success',
          duration: 5000
        })
        this.importShow = false
      }
    })
  }

  private jumpToTransmissionCenter () { // 跳转到传输中心
    this.$router.push('/transmission_center/index/tx_import_task?taskModule=customer')
  }

  private getCusBase () {
    const params = { url: '/server-crm/action/config/customer/basic', method: 'GET' }
    commonAction(params).then(res => {
      if (res.success) {
        this.customerRepeatRules = res.data.customerRepeatRules
      }
    })
  }

  private mounted () {
    this.$getCache('/server-crm/action/config/customer/panel/import', ['customerImports'], false, false, false, 'GET', false, 'data.fields') // 导入字段
    this.getCusBase()
  }
}
</script>

<style lang="stylus" scoped>
.range-area
  margin-top -20px
  .tip
    font-size 12px
    font-family PingFang SC
    font-weight 400
    color #71798c
    line-height 20px
    .import-batch
      display flex
      align-items center
  .btns
    display flex
    justify-content right
.el-input
  width 300px
>>> .moveDialog
  margin-top 40px !important
</style>
